package io.github.jesse205.transferstation.lite.services;

import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import io.github.jesse205.transferstation.lite.activities.DragDropActivity;
import io.github.jesse205.transferstation.lite.activities.DragDropBridgeActivity;
import io.github.jesse205.transferstation.lite.managers.DragDropManager;
import io.github.jesse205.transferstation.lite.sources.PanelSource;

/**
 * 中转站服务
 */
public class DragDropService extends Service {
    private static final String TAG = "DragAndDropService";
    private final PanelSource panelSource = new PanelSource();
    public Intent bridgeActivityIntent;
    private DragAndDropServiceBinder binder;
    @Nullable
    private DragDropActivity activity;
    private boolean isFinishing = false;
    private Configuration oldConfiguration;
    private DragDropManager dragDropManager;

    @Override
    public void onCreate() {
        super.onCreate();
        if (!Settings.canDrawOverlays(this)) {
            stopSelf();
            return;
        }
        Log.v(TAG, "DragAndDropService started.");
        binder = new DragAndDropServiceBinder(this);
        bridgeActivityIntent = new Intent(this, DragDropActivity.class);
        bridgeActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        dragDropManager = DragDropManager.getInstance(this);
        oldConfiguration = new Configuration(getResources().getConfiguration());
    }

    @Override
    public void onDestroy() {
        isFinishing = true;
        super.onDestroy();
        Log.v(TAG, "DragAndDropService stopped.");
        if (activity != null) {
            activity.finishAndRemoveTask();
        }
        dragDropManager.destory();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged: uiMode" + oldConfiguration.uiMode);
        Log.d(TAG, "onConfigurationChanged: " + (oldConfiguration.uiMode != newConfig.uiMode));
        // 检测夜间模式是否变化，以便刷新配色
        if (oldConfiguration.uiMode != newConfig.uiMode
                || oldConfiguration.densityDpi != newConfig.densityDpi
                || oldConfiguration.fontScale != newConfig.fontScale
                || oldConfiguration.getLocales().get(0) != newConfig.getLocales().get(0)) {
            restartBridgeActivity();
        }

        oldConfiguration = new Configuration(newConfig);
        Log.d(TAG, "onConfigurationChanged: uiMode" + newConfig.uiMode);


        if (activity != null) {
            activity.getDragPanelManager().onConfigurationChanged(newConfig);
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public void restartBridgeActivity() {
        if (activity != null) {
            activity.finishAndRemoveTask();
            checkAndStartBridgeActivity();

            // activity.recreate();

            activity = null;
        }
    }

    public void checkAndStartBridgeActivity() {
        if (activity == null && !isFinishing)
            startBridgeActivity();
    }

    public void startBridgeActivity() {
        startActivity(bridgeActivityIntent);
    }


    public static class DragAndDropServiceBinder extends Binder implements DragDropActivity.BridgeCallback {
        private final DragDropService context;
        @Nullable
        private DragDropActivity activity;

        private boolean adsorb = false;

        private DragAndDropServiceBinder(DragDropService context) {
            this.context = context;
        }

        public void setAdsorb(boolean adsorb) {
            this.adsorb = adsorb;
            if (activity != null)
                activity.getDragPanelManager().setAdsorb(adsorb);
        }


        public void openPanel() {
            checkAndStartBridgeActivity();
            // context.panelSource.setState(true);
            if (activity != null) {
                activity.getDragPanelManager().openDragPanel();
            }
        }

        public void closePanel() {
            // context.panelSource.setState(false);
            if (activity != null) {
                activity.getDragPanelManager().closeDragPanel();
            }
        }

        public boolean getPanelPageState() {
            return context.panelSource.getPageState();
        }

        public void setPanelPageState(boolean pageState) {
            context.panelSource.setPageState(pageState);
        }

        public boolean getPanelState() {
            return !(activity == null || activity.getDragPanelManager().isClosing());
        }

        public void clearPanelData() {
            if (activity != null) {
                activity.getDragPanelManager().clearSavedClipData();
            }
        }

        /* @NonNull
        public PropertyChangeSupport getPanelChangeSupport() {
            return context.panelChangeSupport;
        }

        @NonNull
        public PropertyChangeSupport getClipDataChangeSupport() {
            return context.clipDataChangeSupport;
        } */

        @NonNull
        public PanelSource getPanelChangeSource() {
            return context.panelSource;
        }

        @Override
        public void onActivityCreate(DragDropActivity activity, @Nullable Bundle savedInstanceState) {
            Log.d(TAG, "onActivityCreate: " + activity);
            // 强制移除面板，避免崩溃
            if (this.activity != null)
                this.activity.getDragPanelManager().forceRemovePanelFromWindow();
            context.activity = activity;
            this.activity = activity;
            activity.getDragPanelManager().setAdsorb(adsorb);

        }

        @Override
        public void onActivityDestory(DragDropActivity activity) {
            Log.d(TAG, "onActivityDestory: " + activity);
            context.activity = null;
            this.activity = null;
            checkAndStartBridgeActivity();
        }

        public void checkAndStartBridgeActivity() {
            context.checkAndStartBridgeActivity();
        }

        public boolean isFinishing() {
            return context.isFinishing;
        }

        public void startBridgeActivity() {
            context.startBridgeActivity();
        }
    }


}